package com.jilian.powerstation.modul.activity;

import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Paint;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jilian.powerstation.Constant;
import com.jilian.powerstation.MyApplication;
import com.jilian.powerstation.R;
import com.jilian.powerstation.base.BaseActivity;
import com.jilian.powerstation.base.BaseDto;
import com.jilian.powerstation.common.dto.LoginDto;
import com.jilian.powerstation.modul.natives.NativeMainActivity;
import com.jilian.powerstation.modul.viewmodel.UserViewModel;
import com.jilian.powerstation.utils.PinziDialogUtils;
import com.jilian.powerstation.utils.RxTimerUtil;
import com.jilian.powerstation.utils.SPUtil;
import com.jilian.powerstation.utils.ToastUitl;
import com.jilian.powerstation.utils.Utils;
import com.jilian.powerstation.views.ClearEditText;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 登录fff
 * weishixiong
 * 2019-03-17
 */
public class LoginActivity extends BaseActivity {
    private RelativeLayout rlCancel;
    private ClearEditText etMail;
    private EditText etPwd;
    private CheckBox showPwd;
    private ImageView ivEye;
    private TextView tvLoginRegister;
    private TextView tvLoginForgetPwd;
    private TextView tvLogin;
    private boolean mbDisplayFlg;
    private UserViewModel userViewModel;
    private TextView loginLocalMode;
    private TextView loginDemoMode;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    }

    @Override
    protected void onStart() {
        super.onStart();
        MyApplication.clearSpecifyActivities(new Class[]{WelcomeActivity.class});
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        loginDemoMode = (TextView) findViewById(R.id.login_demo_mode);

        showPwd = findViewById(R.id.cb_pwd_show);

          loginLocalMode = (TextView) findViewById(R.id.login_local_mode);
        rlCancel = (RelativeLayout) findViewById(R.id.rl_cancel);
        etMail = (ClearEditText) findViewById(R.id.et_mail);
        etPwd = findViewById(R.id.et_pwd);
        tvLoginRegister = (TextView) findViewById(R.id.tv_login_register);
        tvLoginForgetPwd = (TextView) findViewById(R.id.tv_login_forget_pwd);
        tvLogin = (TextView) findViewById(R.id.tv_login);
//        tvLoginForgetPwd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        String userName = SPUtil.getData(Constant.SP_VALUE.SP_USER, Constant.SP_VALUE.USER_NAME, String.class, "");
//        String pwd = SPUtil.getData(Constant.SP_VALUE.SP_USER, Constant.SP_VALUE.USER_PAD, String.class, "");
        etMail.setText(userName);
        etPwd.setText(pwd);
    }

    @Override
    public void initData() {

    }

    /**
     * 获取本机IP地址
     *
     * @return
     */
    public String getLocalIpAddress() {

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(android.content.Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        try {
            return InetAddress.getByName(String.format("%d.%d.%d.%d",
                    (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
                    (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff))).toString();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取本机的物理地址
     *
     * @return
     */
    public String getLocalMacAddress() {
        WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    private String email;
    private String pwd;

    @Override
    public void initListener() {
        tvLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                email = etMail.getText().toString();
                pwd = etPwd.getText().toString();
                login();

            }
        });

        loginDemoMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                email = "jianyongnan@repower.cn";
             //   email = "demo@sunwoda.com";
                pwd = "123456";
                login();

            }
        });

        loginLocalMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取当前连接的wifi id
                //
                Log.e(TAG, "onClick: " + getLocalIpAddress());
                if (!TextUtils.isEmpty(getLocalIpAddress()) && getLocalIpAddress().contains("10.10.100")) {
                    startActivity(new Intent(LoginActivity.this, NativeMainActivity.class));
                    return;
                } else {
                    ToastUitl.showImageToastTips("Network Connection Failed");
                }

            }
        });
        rlCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        tvLoginRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this, RegistActivity.class));
            }
        });
        etMail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }


            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String pwd = etPwd.getText().toString();
                String emai = etMail.getText().toString();
                if (!TextUtils.isEmpty(etMail.getText().toString()) && !TextUtils.isEmpty(etPwd.getText().toString())) {
                    tvLogin.setBackgroundResource(R.drawable.shape_btn_login_normal);
                    tvLogin.setEnabled(true);
                } else {
                    tvLogin.setBackgroundResource(R.drawable.shape_btn_login_dark);
                    tvLogin.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(etMail.getText().toString()) && !TextUtils.isEmpty(etPwd.getText().toString())) {
                    tvLogin.setBackgroundResource(R.drawable.shape_btn_login_normal);
                    tvLogin.setEnabled(true);
                } else {
                    tvLogin.setBackgroundResource(R.drawable.shape_btn_login_dark);
                    tvLogin.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        tvLoginForgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class));
            }
        });

        showPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                etPwd.setSelection(etPwd.getText().toString().length());
            }
        });
    }

    /**
     * 登录
     */
    private void login() {
        if (pwd.length() < 6 || pwd.length() > 16) {
            ToastUitl.showImageToastTips("Password must be between 6 - 16 characters in length, captital sensitive.");
            return;
        } else if (!Utils.isEmail(email)) {
            ToastUitl.showImageToastTips("Invalid E-Mail Format");
            return;
        }

        showLoadingDialog();
        tvLogin.setEnabled(false);
        userViewModel.login(email, pwd);
        userViewModel.getLoginliveData().observe(this, new Observer<BaseDto<LoginDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<LoginDto> loginDtoBaseDto) {
                hideLoadingDialog();
                tvLogin.setEnabled(true);
                if (loginDtoBaseDto.isSuccess()) {
                    ToastUitl.showImageToastSuccess("Login successful");
                    //保存token到前端
                    SPUtil.putData(Constant.SP_VALUE.SP, Constant.SP_VALUE.TOKEN, loginDtoBaseDto.getData().getToken());
                    SPUtil.putData(Constant.SP_VALUE.SP_USER, Constant.SP_VALUE.USER_NAME, email);
                    SPUtil.putData(Constant.SP_VALUE.SP_USER, Constant.SP_VALUE.USER_PAD, pwd);
                    startActivity(new Intent(LoginActivity.this, EssListActivity.class));
                    finish();
                } else if (loginDtoBaseDto.getCode() == 107) {
                    ToastUitl.showImageToastTips("");
                } else {
                    ToastUitl.showImageToastTips(loginDtoBaseDto.getMsg());
                }
            }
        });
        showLoadingDialog();
    }


}
